package com.mdd.admin.config.wxpay;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.mdd.admin.service.system.ISystemDevPayService;
import com.mdd.admin.vo.system.SystemDevWxPayConfig;
import com.mdd.admin.vo.system.SystemDevWxPayDetailVo;
import com.mdd.common.entity.system.SystemConfig;
import com.mdd.common.mapper.system.SystemConfigMapper;
import com.mdd.common.utils.ConfigUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author panweiliang
 */
@Configuration
@ConditionalOnClass(WxPayService.class)
@AllArgsConstructor
public class WxPayConfiguration {

  @Resource
  private ISystemDevPayService systemDevPayService;

  @Resource
  private SystemConfigMapper systemConfigMapper;

  @Bean
  @ConditionalOnMissingBean
  public WxPayService wxService() {
    WxPayConfig payConfig = new WxPayConfig();
    SystemDevWxPayConfig systemDevWxPayConfig = systemDevPayService.getWxPayConfig(1);
    payConfig.setAppId(StringUtils.trimToNull(getAppId()));
    payConfig.setMchId(StringUtils.trimToNull(systemDevWxPayConfig.getMch_id()));
    payConfig.setApiV3Key(StringUtils.trimToNull(systemDevWxPayConfig.getPay_sign_key()));
    payConfig.setPrivateKeyContent(StringUtils.trimToNull(systemDevWxPayConfig.getApiclient_key()).getBytes());
    payConfig.setPrivateCertContent(StringUtils.trimToNull(systemDevWxPayConfig.getApiclient_cert()).getBytes());
    // 可以指定是否使用沙箱环境
    payConfig.setUseSandboxEnv(false);
    WxPayService wxPayService = new WxPayServiceImpl();
    wxPayService.setConfig(payConfig);
    return wxPayService;
  }

  private String getAppId() {
    List<SystemConfig> configs = systemConfigMapper.selectList(
            new QueryWrapper<SystemConfig>()
                    .select("id", "type", "name", "value")
                    .eq("type", "mp_channel"));

    Map<String, String> map = new LinkedHashMap<>();
    for (SystemConfig config : configs) {
      map.put(config.getName(), config.getValue());
    }
    return map.getOrDefault("appId", "");

  }

}
